package com.example.auth.security;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
public class RedisSecurityContextRepository implements SecurityContextRepository {

    private static final String SECURITY_CONTEXT_KEY_PREFIX = "security:context:";
    private static final long TIMEOUT = 3600; // 1小时过期

    private final RedisTemplate<String, SecurityContext> redisTemplate;

    @Override
    public SecurityContext loadContext(HttpServletRequest request) {
        String token = extractToken(request);
        if (token != null) {
            SecurityContext context = redisTemplate.opsForValue().get(SECURITY_CONTEXT_KEY_PREFIX + token);
            if (context != null) {
                return context;
            }
        }
        return SecurityContextHolder.createEmptyContext();
    }

    @Override
    public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) {
        String token = extractToken(request);
        if (token != null && context != null && context.getAuthentication() != null) {
            redisTemplate.opsForValue().set(
                SECURITY_CONTEXT_KEY_PREFIX + token,
                context,
                TIMEOUT,
                TimeUnit.SECONDS
            );
        }
    }

    @Override
    public boolean containsContext(HttpServletRequest request) {
        String token = extractToken(request);
        return token != null && Boolean.TRUE.equals(
            redisTemplate.hasKey(SECURITY_CONTEXT_KEY_PREFIX + token)
        );
    }

    private String extractToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
} 